package com.example.blog.controller;

import com.example.blog.entity.Article;
import com.example.blog.mapper.ArticleMapper;
import com.example.blog.service.impl.ArticleServiceImpl;
import com.yc.common.vo.Result;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 刘扬新
 * @since 2023-06-27
 */
@RestController
@RequestMapping("/blog/article")
public class ArticleController {

    @Resource
    ArticleServiceImpl articleService;

    @Resource
    ArticleMapper articleMapper;

    @RequestMapping("save")
    public Result save(@RequestBody @Valid Article article, Errors errors) {
        if (errors.hasFieldErrors()) {
            return Result.failure("文章提交数据错误!",errors.getAllErrors());
        }
        article.setStatus("1");
        articleService.saveOrUpdate(article);
        return Result.success("文章添加成功");
    }


    //主页文章查询  查全部
    @RequestMapping("selectPage")
    public Result selectPage(int page,
                             @RequestParam(defaultValue = "4") int size){
        if (articleService.selectPage(page,size).size() != 0 && articleService.selectPage(page, size) != null){
            List<Map<String,Object>> articles = articleService.selectPage(page,size);
            return Result.success("查询成功",articles);
        }
        return Result.failure("查询失败！");
    }

    //文章查询  根据栏目id查  grupe  by
    @RequestMapping("selectPageById")
    public Result selectPage(int id,int currentPage,int pagesize ){
        if (articleService.selectPage(id,currentPage,pagesize) != null){
            List<Map<String,Object>> articles = articleService.selectPage(id,currentPage,pagesize);
            return Result.success("查询成功",articles);
        }
        return Result.failure("查询失败！");
    }

    //根据文章id查文章
    @RequestMapping("/selectById")
    public Result selectById(int id){
        if (articleService.selectById(id) != null){
            return Result.success("查询成功",articleService.selectById(id));
        }else {
            return Result.failure("查询失败！");
        }
    }
}
